<template>
  <div class="add-enterprise">
    <header class="add-header">
      <div class="left">
        <span class="arrow" @click="$router.back()"><i class="el-icon-arrow-left" />返回</span>
        <span>|</span>
        <span>{{ id ? '编辑企业' : '新增企业' }}</span>
      </div>
      <div class="right">
        黑马程序员
      </div>
    </header>
    <main v-loading="loading" class="add-main" element-loading-text="加载中...">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form ref="ruleForm" label-width="100px" :rules="addRules" :model="addForm">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode" placeholder="请选择行业">
                <el-option
                  v-for="item in industryList"
                  :key="item.industryCode"
                  :label="item.industryName"
                  :value="item.industryCode"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" />
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseId">
              <el-upload
                action="#"
                :http-request="uploadRequest"
                :before-upload="beforeUpload"
                :file-list="fileList"
                :limit="1"
                list-type="text"
                show-file-list
                :on-preview="handlePreview"
                :disabled="fileList.length > 0"
                :auto-upload="true"
              >
                <el-button
                  size="small"
                  :type="fileList.length ? 'success' : 'primary'"
                  :plain="!!fileList.length"
                  :disabled="fileList.length > 0"
                >{{ fileList.length ? '已上传' : '点击上传' }}</el-button>
                <template #tip>
                  <div class="el-upload__tip">支持扩展名：.png .jpg .jpeg，文件大小不超过5M</div>
                </template>
                <template #file="{ file }">
                  <div class="upload-file fileBox">
                    <span>{{ file.name }}</span>
                    <span class="operation">
                      <el-button type="text" class="el-icon-view btnDel" @click="handlePreview(file)" />
                      <el-button type="text" class="el-icon-delete btnDel" @click="handleRemove" />
                    </span>
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="resetForm">重置</el-button>
        <el-button type="primary" @click="confirmSubmit">确定</el-button>
      </div>
    </footer>
    <el-image-viewer
      v-if="showViewer"
      :url-list="[previewUrl]"
      :on-close="() => showViewer = false"
    />
  </div>
</template>

<script>
import { getIndustryListAPI, uploadAPI, createExterpriseAPI, getIndustryDetailAPI, updateExterpriseAPI } from '@/api/enterprise'
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'

export default {
  name: 'EnterpriseAdd',
  components: { ElImageViewer },
  data() {
    const validatePhone = (rule, value, callback) => {
      /^1[3-9]\d{9}$/.test(value) ? callback() : callback(new Error('请输入正确的手机号'))
    }

    return {
      fileList: [],
      loading: false,
      showViewer: false,
      previewUrl: '',
      industryList: [],
      addForm: {
        name: '',
        legalPerson: '',
        registeredAddress: '',
        industryCode: '',
        contact: '',
        contactNumber: '',
        businessLicenseUrl: '',
        businessLicenseId: ''
      },
      addRules: {
        name: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
        legalPerson: [{ required: true, message: '请输入法人', trigger: 'blur' }],
        registeredAddress: [{ required: true, message: '注册地址为必填', trigger: 'blur' }],
        industryCode: [{ required: true, message: '所在行业为必填', trigger: 'change' }],
        contact: [{ required: true, message: '企业联系人为必填', trigger: 'blur' }],
        contactNumber: [
          { required: true, message: '企业联系人电话为必填', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }
        ],
        businessLicenseId: [{ required: true, message: '请上传营业执照', trigger: 'blur' }]
      }
    }
  },
  computed: {
    id() {
      return this.$route.query.id
    }
  },
  created() {
    this.getIndustryList()
    this.id && this.getExterpriseDetail(this.id)
  },
  methods: {
    async getIndustryList() {
      const { data } = await getIndustryListAPI()
      this.industryList = data
    },
    async getExterpriseDetail(id) {
      this.loading = true
      try {
        const { data } = await getIndustryDetailAPI(id)
        this.addForm = data
        if (data.businessLicenseUrl) {
          this.fileList = [{
            name: data.businessLicenseName || '营业执照',
            url: data.businessLicenseUrl
          }]
        }
      } finally {
        this.loading = false
      }
    },
    beforeUpload(file) {
      const allowImgType = ['image/jpeg', 'image/png', 'image/jpg'].includes(file.type)
      const isLt5M = file.size / 1024 / 1024 < 5

      !allowImgType && this.$message.error('上传图片只能是 JPG、PNG、JPEG 格式!')
      !isLt5M && this.$message.error('上传图片大小不能超过 5MB!')

      return allowImgType && isLt5M
    },
    async uploadRequest({ file }) {
      const formData = new FormData()
      formData.append('file', file)
      formData.append('type', 'businessLicense')

      try {
        const { data } = await uploadAPI(formData)
        this.addForm.businessLicenseId = data.id
        this.addForm.businessLicenseUrl = data.url
        this.fileList = [{ name: file.name, url: data.url }]
        this.$refs.ruleForm.validateField('businessLicenseId')
        this.$message.success('上传成功')
      } catch (error) {
        this.$message.error('上传失败')
      }
    },
    handleRemove() {
      this.fileList = []
      this.addForm.businessLicenseId = ''
      this.addForm.businessLicenseUrl = ''
      this.$refs.ruleForm.validateField('businessLicenseId')
    },
    handlePreview(file) {
      this.previewUrl = file.url
      this.showViewer = true
    },
    resetForm() {
      this.$refs.ruleForm.resetFields()
      this.fileList = []
    },
    confirmSubmit() {
      this.$refs.ruleForm.validate(async valid => {
        if (!valid) return

        try {
          if (this.id) {
            const formData = { ...this.addForm }
            delete formData.businessLicenseName
            delete formData.industryName
            delete formData.rent
            await updateExterpriseAPI(formData)
          } else {
            await createExterpriseAPI(this.addForm)
          }

          this.$message.success(this.id ? '修改成功' : '新增成功')
          this.$router.back()
        } catch (error) {
          this.$message.error('操作失败，请重试')
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.add-enterprise {
    background-color: #f4f6f8;
    height: 100vh;

    .add-header {
        display: flex;
        justify-content: space-between;
        padding: 0 20px;
        height: 64px;
        line-height: 64px;
        font-size: 16px;
        font-weight: bold;
        background-color: #fff;

        .left {
            span {
                margin-right: 4px;
            }

            .arrow {
                cursor: pointer;
            }
        }

        .right {
            text-align: right;
        }
    }

    .add-main {
        background: #f4f6f8;
        padding: 20px 130px;

        .form-container {
            background-color: #fff;

            .title {
                height: 60px;
                line-height: 60px;
                padding-left: 20px;
            }

            .form {
                margin-bottom: 20px;
                padding: 20px 65px 24px;

                .el-form {
                    display: flex;
                    flex-wrap: wrap;

                    .el-form-item {
                        width: 50%;
                    }
                }
            }
        }
    }

    .add-footer {
        position: fixed;
        bottom: 0;
        width: 100%;
        padding: 24px 50px;
        color: #000000d9;
        font-size: 14px;
        background: #fff;
        text-align: center;
    }
    .fileBox{
      display: flex;
      justify-content: space-between;
      align-items: center;

      .btnDel{
      margin-right: 20px;
      vertical-align: middle;
      color: #606266;
    }
    }

}
</style>
